package com.andrew.service.impl;

import cn.hutool.core.util.StrUtil;
import com.andrew.common.Constant;
import com.andrew.common.ResponseCode;
import com.andrew.exception.ServiceException;
import com.andrew.util.RedisService;
import com.andrew.service.TokenService;
import com.andrew.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisService redisService;


    /**
     * 创建token
     *
     * @return
     */
    @Override
    public String createToken() {
        String token = RandomUtil.randomUUID();
        try {
            redisService.setEx(token, token,10000L);
            return token;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * 检验token
     *
     * @param request
     * @return
     */
    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {

        String token = request.getHeader(Constant.TOKEN_NAME);
        if (StrUtil.isBlank(token)) {// header中不存在token
            token = request.getParameter(Constant.TOKEN_NAME);
            if (StrUtil.isBlank(token)) {// parameter中也不存在token
                throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
        }

        if (!redisService.exists(token)) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getCode(), ResponseCode.REPETITIVE_OPERATION.getMsg());
        }

        boolean remove = redisService.remove(token);
        if (!remove) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getCode(), ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
        return true;
    }

}
